package com.ficus.road.maintain.authority.controller;

import com.alibaba.fastjson.JSONObject;
import com.ficus.road.maintain.authority.dto.UserDTO;
import com.ficus.road.maintain.authority.service.UserService;
import com.ficus.road.maintain.authority.utils.JwtUtil;
import com.ficus.road.maintain.authority.vo.LoginRequest;
import com.ficus.road.maintain.core.model.common.ErrorCodeDTO;
import com.ficus.road.maintain.core.model.common.ErrorDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

/**
 * @author hao.zhou1
 * @date 2021/12/9 下午4:57
 */
@RestController
public class LoginController {
    @Autowired
    private UserService userService;

    @ResponseBody
    @RequestMapping(value = "/system/login", method = RequestMethod.POST)
    public ResponseEntity login(@RequestBody LoginRequest loginRequest) {

        JSONObject json = new JSONObject();
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        UserDTO userDTO = userService.queryUserByUsername(loginRequest.getUsername());
        if (userDTO != null) {
            String dbPassWord = userDTO.getPassword();
            if (bCryptPasswordEncoder.matches(loginRequest.getPassword(), dbPassWord)) {
                //创建token
                String token = JwtUtil.generateToken(loginRequest.getUsername());
                json.put(JwtUtil.AUTHORIZATION, token);
                return new ResponseEntity<>(json, HttpStatus.OK);
            }
        }
        return new ResponseEntity<>(ErrorDTO.builder().message("login fail!").retryable(false).code(ErrorCodeDTO.SERVER_BUSY).build(), HttpStatus.INTERNAL_SERVER_ERROR);
    }
}
